const axios = require('axios');
const path = require('path');
const fs = require('fs');
// const { exec } = require('child_process');
const { promisify } = require('util');
const exec = promisify(require('child_process').exec);

const url = 'https://mmbiz.qpic.cn/mmbiz_png/LJeRyqxLu96DtyXjkqY4mEMh2ibmhCayOk9yqQzJicgO4MYkDcmfPcRhk49FUN8wmdicss4lCuTzdiaLxicoVu27B5Q/640?wx_fmt=png'

async function downloadImage(url, folder, name) {
  try {
    const response = await axios.get(url, {
      responseType: 'stream'
    });

    const contentType = response.headers['content-type'];
    const extension = getExtensionFromContentType(contentType);
    const fullFileName = `${name}.${extension}`;
    const filePath = path.join(folder, fullFileName);


    // 创建目录（如果不存在）
    if (!fs.existsSync(folder)) {
      fs.mkdirSync(folder, { recursive: true });
    }

    const writer = fs.createWriteStream(filePath);
    response.data.pipe(writer);

    // 返回一个 Promise，以便在文件写入完成后解析
    return new Promise((resolve, reject) => {
      writer.on('finish', async () => {
        if (extension === 'webp') {

          const pngImgName = `${name}.png`
          const pngFilePath = path.join(folder, pngImgName);
          await exec(`convert ${filePath} ${pngFilePath}`);
          fs.unlinkSync(filePath); // 删除临时文件
          console.log(`Done: ${pngFilePath}`);
          resolve(pngImgName)
          return
        }
        console.log(`Done: ${filePath}`);
        resolve(fullFileName); // 文件写入完成后解析 Promise
      });

      writer.on('error', (err) => {
        console.error(`下载出错: ${err.message}`);
        reject(err); // 写入出错时拒绝 Promise
      });
    });
  } catch (error) {
    console.error(`请求失败: ${error.message}`);
    throw error; // 抛出错误以便外部捕获
  }

}

// 根据 Content-Type 获取文件扩展名
function getExtensionFromContentType(contentType) {
  const typeMap = {
    'image/jpeg': 'jpg',
    'image/png': 'png',
    'image/gif': 'gif',
    'image/webp': 'webp',
    'image/svg+xml': 'svg',
    'application/pdf': 'pdf',
    // 添加更多类型映射
  };
  return typeMap[contentType] || 'bin'; // 默认使用 'bin'
}


// const imagesDir = path.join(__dirname, 'images');
// downloadImage(url, 'images', 'test.png')

module.exports = { downloadImage }
